<?php
	require_once("../shared/database.php");
	// Do our best to finish as many matches as possible
	
	$query = "SELECT `matches`.id AS match_id, `items`.id AS item_id, `hash`, `items`.label AS label, `birth_date`, `death_date`, `verified_match` FROM `matches` LEFT JOIN (`items`) ON items.match_id = matches.id  WHERE items.verified_match = 1 AND (matches.scripted = 1 OR matches.finished = 1) ORDER BY matches.id ASC";
	
	// $result = Database::instance()->select(array(
	// 		"matches.id" => "match_id",
	// 		"items.id" => "item_id",
	// 		"hash",
	// 		"items.label" => "label",
	// 		"birth_date",
	// 		"death_date",
	// 		"verified_match"
	// 	))->from('matches')->leftjoin('items', array('items.match_id', 'matches.id'))->where(array('items.verified_match' => 1, 'matches.finished !=' => 1))->orderby('matches.id')->get();
	
	Database::instance()->query("SET NAMES 'utf8'");
	$result = Database::instance()->query($query);

	$match_id = null;
	$person_data = null;
	$items = array();
	
	$doc = new DomDocument('1.0');
	$root = $doc->createElement('musicnet');
	$root = $doc->appendChild($root);
	
	$count = 0;
	
	while($row = mysql_fetch_assoc($result))
	{
		if($row['match_id'] != $match_id)
		{
			// We've found a new match
			
			// Update the last match we looked over
			if(!empty($match_id))
			{
				$count++;
				
				$match = $doc->createElement('person');
				
				$attr = $doc->createAttribute('musicnetid');
				$attr->appendChild($doc->createTextNode(preg_replace("/^musicnet/", "", $person_data['match_id'])));
				$match->appendChild($attr);
				
				$label = $doc->createElement('label');
				$label->appendChild($doc->createTextNode($person_data['label']));
				$match->appendChild($label);
				
				$birthdate = $doc->createElement('birthdate');
				$birthdate->appendChild($doc->createTextNode($person_data['birth_date']));
				$match->appendChild($birthdate);
				
				$deathdate = $doc->createElement('deathdate');
				$deathdate->appendChild($doc->createTextNode($person_data['death_date']));
				$match->appendChild($deathdate);
				
				$variations = $doc->createElement('namevariants');
				$match->appendChild($variations);
				
				// Handle name variations & Links to catalogs
				foreach($items as $catalog => $metadata_array)
				{
					foreach($metadata_array as $metadata)
					{
						// Variations
						$v = $doc->createElement('variant');
						
						$attr = $doc->createAttribute('catalog');
						$attr->appendChild($doc->createTextNode($catalog));
						$v->appendChild($attr);
						
						// Clean up the URLS
						$url = $metadata['Info'];
						
						if($catalog == "copac")
							$url = "http://copac.ac.uk/search?au=".urlencode($metadata['label']);
						else if($catalog == "rism")
							$url = "http://www.rism.org.uk/search/quick?person=".urlencode($metadata['label']);
						else if($catalog == "blcollection")
							$url =  "http://catalogue.bl.uk/F/?func=find-b&request=".urlencode($metadata['label'])."&find_code=WNA";
						
						$link = $doc->createAttribute('url');
						$link->appendChild($doc->createTextNode($url));
						$v->appendChild($link);

						$v->appendChild($doc->createTextNode($metadata['label']));

						$variations->appendChild($v);
					}
				}
				
				$root->appendChild($match);
			}
			
			// Update the match_id variable
			$person_data = $row;
			$match_id = $row['match_id'];
			$items = array();
		}
		
		$metadata_result = Database::instance()->select('*')->from('metadata')->where(array('item_id' => $row['item_id']))->get();
		$metadata = array();		
		
		while($meta_row = mysql_fetch_assoc($metadata_result))
			$metadata[$meta_row['key']] = $meta_row['value'];
			
		$metadata['label'] = $row['label'];

		$cat = strtolower(preg_replace("/[^a-zA-Z]/", "", $metadata['X0']));
		
		if(strpos($cat, 'copac') !== FALSE)
			$cat = 'copac';
		
		if(!isset($items[$cat]))
			$items[$cat] = array();
			
		$items[$cat][] = $metadata;
	}
	
	echo $doc->saveXML();
	//echo "Exported $count items";
?>